package com.boruan.qq.zxgylibrary.ui.activities;

import android.annotation.SuppressLint;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.net.Uri;
import android.net.http.SslError;
import android.os.Build;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.RequiresApi;
import android.util.Log;
import android.util.TypedValue;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.webkit.JavascriptInterface;
import android.webkit.SslErrorHandler;
import android.webkit.ValueCallback;
import android.webkit.WebResourceError;
import android.webkit.WebResourceRequest;
import android.webkit.WebResourceResponse;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.TextView;
import android.widget.Toast;

import com.boruan.qq.zxgylibrary.R;
import com.boruan.qq.zxgylibrary.R2;
import com.boruan.qq.zxgylibrary.base.BaseActivity;
import com.boruan.qq.zxgylibrary.constants.ConstantInfo;
import com.boruan.qq.zxgylibrary.ui.widgets.CommonDialog;
import com.boruan.qq.zxgylibrary.utils.CallPhoneUtils;
import com.boruan.qq.zxgylibrary.utils.CustomDialog;
import com.boruan.qq.zxgylibrary.utils.RequestPermissionType;

import butterknife.BindView;
import butterknife.OnClick;

import static com.boruan.qq.zxgylibrary.utils.RequestPermissionType.REQUEST_CODE_ORDER_DETAIL;

/**
 * Created by 崔琦 on 2019/8/13.
 * des: 订单详情页面
 */

public class OrderDetailActivity extends BaseActivity {
    @BindView(R2.id.tv_order_status)
    TextView tvOrderStatus;
    @BindView(R2.id.ll_add_web)
    LinearLayout llAddWeb;

    private CustomDialog customDialog;
    private String orderStatus;
    private String orderId;

    private String intentStatus;

    @Override
    protected int getLayoutId() {
        if (Build.VERSION.SDK_INT >= 21) {
            View decorView = getWindow().getDecorView();
            decorView.setSystemUiVisibility(View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN | View.SYSTEM_UI_FLAG_LAYOUT_STABLE);
            getWindow().setStatusBarColor(Color.TRANSPARENT);
        }
        return R.layout.drug_activity_drug_order_detail;
    }

    @Override
    protected void init(Bundle savedInstanceState) {
        ConstantInfo.isDetailRefresh = true;
        customDialog = new CustomDialog(this,R.style.CustomDialog);
        customDialog.show();
        if (getIntent() != null){
            intentStatus = getIntent().getStringExtra("orderStatus");
            orderId = getIntent().getStringExtra("orderId");
            if ("1".equals(intentStatus)){
                tvOrderStatus.setText("待付款");
                orderStatus = "waitReceipt";
            }else if ("2".equals(intentStatus)){
                tvOrderStatus.setText("待配送");
                orderStatus = "waitReceipt";
            }else if ("3".equals(intentStatus)){
                tvOrderStatus.setText("配送中");
                orderStatus = "waitReceipt";
            }else if ("4".equals(intentStatus)){
                tvOrderStatus.setText("待评价");
                orderStatus = "waitReceipt";
            }else if ("5".equals(intentStatus)){
                tvOrderStatus.setText("订单已送达");
                orderStatus = "waitReceipt";
            }else if ("6".equals(intentStatus)){
                tvOrderStatus.setText("订单已取消");
                orderStatus = "waitReceipt";
            }else if ("7".equals(intentStatus)){
                tvOrderStatus.setText("已关闭");
                orderStatus = "waitReceipt";
            }else if ("20".equals(intentStatus)){
                tvOrderStatus.setText("待商家接单");
                orderStatus = "waitReceipt";
            }else if ("21".equals(intentStatus)){
                tvOrderStatus.setText("支付处理中");
                orderStatus = "waitReceipt";
            }else if ("22".equals(intentStatus)){
                tvOrderStatus.setText("退款申请中");
                orderStatus = "waitReceipt";
            }else if ("23".equals(intentStatus)){
                tvOrderStatus.setText("订单已取消");
                orderStatus = "waitReceipt";
            }else if ("24".equals(intentStatus)){
                tvOrderStatus.setText("退款被拒绝");
                orderStatus = "waitReceipt";
            }else if ("30".equals(intentStatus)){
                tvOrderStatus.setText("支付失败 ");
                orderStatus = "waitReceipt";
            }else if ("31".equals(intentStatus)){
                tvOrderStatus.setText("配送异常");
                orderStatus = "waitReceipt";
            }else if ("99".equals(intentStatus)){
                tvOrderStatus.setText("支付完成");
                orderStatus = "waitReceipt";
            }else if ("100".equals(intentStatus)){
                tvOrderStatus.setText("到店自取");
                orderStatus = "waitReceipt";
            }
        }
        initCommonWeb(ConstantInfo.baseUrl + orderStatus + "?type=android&orderId=" + orderId + "&token=" + ConstantInfo.h5UserToken);

    }

    @OnClick(R2.id.iv_back)
    public void onViewClicked() {
        finish();
    }

    /**
     * 初始化web
     */
    @SuppressLint("JavascriptInterface")
    private void initCommonWeb(final String richText){
        commonWeb.loadUrl(richText);
        commonWeb.addJavascriptInterface(OrderDetailActivity.this, "control");
        commonWeb.setWebViewClient(new WebViewClient(){
            @Override
            public void onPageFinished(WebView view, String url) {
                super.onPageFinished(view, url);
                customDialog.dismiss();
            }

            @Override
            public void onPageStarted(WebView view, String url, Bitmap favicon) {
                super.onPageStarted(view, url, favicon);
                //dialog.show();
            }

            @Override
            public void onReceivedSslError(WebView view, SslErrorHandler handler, SslError error) {
                handler.proceed();//接受所有网站的证书，忽略SSL错误
                
            }

            @RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
            @Override
            public void onReceivedError(WebView view, WebResourceRequest webResourceRequest, WebResourceError webResourceError) {
                super.onReceivedError(view, webResourceRequest, webResourceError);
                if (webResourceRequest.isForMainFrame()) {
//					view.loadUrl("about:blank");// 避免出现默认的错误界面
//                    Toast.makeText(OrderDetailActivity.this, "网络加载异常，请稍后重试！", Toast.LENGTH_SHORT).show();
                }
            }

            @Override
            public void onReceivedError(WebView view, int errorCode, String description, String failingUrl) {
                super.onReceivedError(view, errorCode, description, failingUrl);
                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
                    return;
                }
//				view.loadUrl("about:blank");// 避免出现默认的错误界面
//                Toast.makeText(OrderDetailActivity.this, "网络加载异常，请稍后重试！", Toast.LENGTH_SHORT).show();
            }
			@RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
            @Override
            public void onReceivedHttpError(WebView view, WebResourceRequest request, WebResourceResponse errorResponse) {
                super.onReceivedHttpError(view, request, errorResponse);
                // 这个方法在 android 6.0才出现
                int statusCode = errorResponse.getStatusCode();
                if (404 == statusCode || 500 == statusCode) {
//                    view.loadUrl("about:blank");// 避免出现默认的错误界面
                }
            }
        });
        llAddWeb.addView(commonWeb);
    }

    @JavascriptInterface
    public void goToPay(String id,String shopName,String money){
        //用户从订单里面去支付
        Intent intent = new Intent(OrderDetailActivity.this,PayCheckStandActivity.class);
        intent.putExtra("orderId",id);
        intent.putExtra("money",money);
        intent.putExtra("shopName",shopName);
        startActivity(intent);
        finish();
    }

    @JavascriptInterface
    public void cancelOrder(String id){
        orderId = id;
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                popPromptCancelOrder();
            }
        });
    }

    @JavascriptInterface
    public void clickEnterPharmacy(String id){//点击进入药店详情
        Log.i("id",id + "lala");
        Intent intent = new Intent(OrderDetailActivity.this, PharmacyHomePageActivity.class);
        intent.putExtra("id",id);
        startActivity(intent);
    }

    private String mobile;
    @JavascriptInterface
    public void contactMerchant(final String mPhone){
        mobile = mPhone;
        Log.i("mobile",mobile);

        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                new CommonDialog.Builder(OrderDetailActivity.this).setCanceledOnTouchOutside(false)
                        .setTitle("友情提示")
                        .setMessage("确定要给商家打电话吗？\n商家电话：" + mPhone)
                        .setPositiveButton("确定", new View.OnClickListener() {
                            @Override
                            public void onClick(View view) {
                                CallPhoneUtils.requestPermission(mPhone,OrderDetailActivity.this);
                            }
                        }).setNegativeButton("取消", null).show();
            }
        });

    }

    @JavascriptInterface
    public void modifyOrderInfo(String id){
        Log.i("id",id + "lala");
        Intent intent = new Intent(OrderDetailActivity.this, ModifyOrderInfoActivity.class);
        intent.putExtra("id",id);
        startActivityForResult(intent,REQUEST_CODE_ORDER_DETAIL);
    }

    @JavascriptInterface
    public void clickToEvaluation(String id){
        Log.i("id",id + "lala");
        Intent intent = new Intent(OrderDetailActivity.this, OrderEvaluationActivity.class);
        intent.putExtra("id",id);
        startActivityForResult(intent,REQUEST_CODE_ORDER_DETAIL);
    }

    @JavascriptInterface
    public void undoCancelApply(String id){
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                popUndoApply();
            }
        });
    }

    @JavascriptInterface
    public void lookRefundProgress(String id){
        Intent intent = new Intent(OrderDetailActivity.this,RefundProgressActivity.class);
        startActivity(intent);
    }

    @JavascriptInterface
    public void clickEnterAfterSales(String id){
        Intent intent = new Intent(OrderDetailActivity.this,AfterSalesActivity.class);
        startActivity(intent);
    }

    @JavascriptInterface
    public void clickEnterReturn(String id){
        Intent intent = new Intent(OrderDetailActivity.this,OrderReturnActivity.class);
        intent.putExtra("id",id);
        startActivityForResult(intent,REQUEST_CODE_ORDER_DETAIL);
    }


    /**
     * 弹出取消申请
     * */
    private void popUndoApply() {
        final PopupWindow undoApplyWindow = new PopupWindow();
        View convertView = LayoutInflater.from(this).inflate(R.layout.drug_pop_undo_apply,null);
        TextView okUndo = (TextView)convertView.findViewById(R.id.ok_undo);
        TextView noUndo = (TextView)convertView.findViewById(R.id.no_undo);

        undoApplyWindow.setContentView(convertView);
        okUndo.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                /** 需要更新订单状态 */
                //initCommonWeb("");
                Toast.makeText(OrderDetailActivity.this, "更新订单状态", Toast.LENGTH_SHORT).show();
                undoApplyWindow.dismiss();
            }
        });

        noUndo.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                undoApplyWindow.dismiss();
            }
        });
        undoApplyWindow.setWidth(ConstantInfo.screenWidth - getPxFromDp(80));
        undoApplyWindow.setHeight(WindowManager.LayoutParams.WRAP_CONTENT);
        undoApplyWindow.setBackgroundDrawable(new ColorDrawable(0x00000000));
        undoApplyWindow.setTouchable(true);
        undoApplyWindow.setOutsideTouchable(true);
        /** 设置popupWindow动画 */
        undoApplyWindow.setAnimationStyle(R.style.style_down_to_up_animation);
        //不设置焦点的话点击外面dismiss的同时会响应外层的触摸事件
        backgroundAlpha(0.3f);
        undoApplyWindow.setFocusable(false);
        undoApplyWindow.showAtLocation(findViewById(R.id.rl_detail), Gravity.CENTER,0,0);
        undoApplyWindow.setOnDismissListener(new poponDismissListener());
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        if (requestCode == RequestPermissionType.REQUEST_CODE_ASK_CALL_PHONE){
            for(int i=0;i<grantResults.length;i++){
                if(grantResults[i]== PackageManager.PERMISSION_GRANTED){
                    startActivity(new Intent(Intent.ACTION_CALL).setData(Uri.parse("tel:"+ mobile)));
                } else {

                }
            }
        }
    }

    /**
     * 弹出提示是否取消订单
     * */
    private void popPromptCancelOrder(){
        final PopupWindow cancelWindow = new PopupWindow();
        View convertView = LayoutInflater.from(this).inflate(R.layout.drug_pop_prompt_cancel_order,null);
        Button btnOk = (Button)convertView.findViewById(R.id.btn_ok);
        ImageView ivDelete = (ImageView)convertView.findViewById(R.id.iv_delete);

        cancelWindow.setContentView(convertView);
        btnOk.setOnClickListener(new View.OnClickListener() {
            @RequiresApi(api = Build.VERSION_CODES.KITKAT)
            @Override
            public void onClick(View view) {
                /** 调接口执行取消操作 */
                commonWeb.evaluateJavascript("window.cancel()", new ValueCallback<String>() {
                    @Override
                    public void onReceiveValue(String s) {
                        Log.i("error",s);
                    }
                });
                cancelWindow.dismiss();
                Intent intent = new Intent(OrderDetailActivity.this,CancelReasonActivity.class);
                intent.putExtra("orderId",orderId);
                startActivityForResult(intent,REQUEST_CODE_ORDER_DETAIL);
            }
        });

        ivDelete.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                cancelWindow.dismiss();
            }
        });
        cancelWindow.setWidth(ConstantInfo.screenWidth - getPxFromDp(80));
        cancelWindow.setHeight(WindowManager.LayoutParams.WRAP_CONTENT);
        cancelWindow.setBackgroundDrawable(new ColorDrawable(0x00000000));
        cancelWindow.setTouchable(true);
        cancelWindow.setOutsideTouchable(true);
        /** 设置popupWindow动画 */
        cancelWindow.setAnimationStyle(R.style.style_down_to_up_animation);
        //不设置焦点的话点击外面dismiss的同时会响应外层的触摸事件
        backgroundAlpha(0.3f);
        cancelWindow.setFocusable(false);
        cancelWindow.showAtLocation(findViewById(R.id.rl_detail), Gravity.CENTER,0,0);
        cancelWindow.setOnDismissListener(new poponDismissListener());
    }

    /**
     * 得到dp转化成的px
     * */
    public int getPxFromDp(float dip) {
        float result = TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, dip, getResources().getDisplayMetrics());
        return (int) result;
    }

    /**
     * PopupWindow背景变暗
     */
    public void backgroundAlpha(float bgAlpha) {
        WindowManager.LayoutParams lp = getWindow().getAttributes();
        lp.alpha = bgAlpha; //0.0-1.0
        getWindow().setAttributes(lp);
    }

    class poponDismissListener implements PopupWindow.OnDismissListener {
        @Override
        public void onDismiss() {
            // TODO Auto-generated method stub
            backgroundAlpha(1f);
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == REQUEST_CODE_ORDER_DETAIL && resultCode == 12){
            llAddWeb.removeAllViews();
            tvOrderStatus.setText("订单已取消");
            orderStatus = "waitReceipt";
            initCommonWeb(ConstantInfo.baseUrl + orderStatus + "?type=android&orderId=" + orderId + "&token=" + ConstantInfo.h5UserToken);

        }else if (requestCode == REQUEST_CODE_ORDER_DETAIL && resultCode == 16){
            /** 重新刷新页面 */

        }else if (requestCode == REQUEST_CODE_ORDER_DETAIL && resultCode == 13){
            finish();
        }else if (requestCode == REQUEST_CODE_ORDER_DETAIL && resultCode == 15){//退完款以后返回
            llAddWeb.removeAllViews();
            tvOrderStatus.setText("已关闭");
            orderStatus = "waitReceipt";
            initCommonWeb(ConstantInfo.baseUrl + orderStatus + "?type=android&orderId=" + orderId + "&token=" + ConstantInfo.h5UserToken);
			if (commonWeb != null){
                commonWeb.reload();
            }
        }
    }

    @Override
    protected void onDestroy() {
        Log.i("测试","ondes");
        if (commonWeb != null) {
            //加载null内容
            commonWeb.loadDataWithBaseURL(null, "", "text/html", "utf-8", null);
            //清除历史记录
            commonWeb.clearHistory();
            //移除WebView
            ((ViewGroup) commonWeb.getParent()).removeView(commonWeb);
            //销毁VebView
            commonWeb.destroy();
            //WebView置为null
            commonWeb = null;
        }
        super.onDestroy();
    }
}
